<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>入门指南 - The Rust Rand Book</title>
        
        


        <!-- Custom HTML head -->
        


        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="Extended documentation for Rust&#x27;s Rand lib">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        
        <link rel="icon" href="favicon.svg">
        
        
        <link rel="shortcut icon" href="favicon.png">
        
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        
        <link rel="stylesheet" href="fonts/fonts.css">
        

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        

        
    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><a href="intro.html">介绍</a></li><li class="chapter-item expanded "><a href="guide-start.html" class="active"><strong aria-hidden="true">1.</strong> 入门指南</a></li><li class="chapter-item expanded "><a href="crates.html"><strong aria-hidden="true">2.</strong> crate 和特性</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="crates-rand.html"><strong aria-hidden="true">2.1.</strong> 随机加密(co)</a></li><li class="chapter-item expanded "><a href="crates-gen.html"><strong aria-hidden="true">2.2.</strong> 随机信号生成器</a></li></ol></li><li class="chapter-item expanded "><a href="guide.html"><strong aria-hidden="true">3.</strong> 指南</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="guide-data.html"><strong aria-hidden="true">3.1.</strong> 随机数据</a></li><li class="chapter-item expanded "><a href="guide-gen.html"><strong aria-hidden="true">3.2.</strong> 生成器类型</a></li><li class="chapter-item expanded "><a href="guide-rngs.html"><strong aria-hidden="true">3.3.</strong> 随机数生成器(RNGs)</a></li><li class="chapter-item expanded "><a href="guide-seeding.html"><strong aria-hidden="true">3.4.</strong> 为随机数生成器置种</a></li><li class="chapter-item expanded "><a href="guide-values.html"><strong aria-hidden="true">3.5.</strong> 随机值</a></li><li class="chapter-item expanded "><a href="guide-dist.html"><strong aria-hidden="true">3.6.</strong> 各种分布方式</a></li><li class="chapter-item expanded "><a href="guide-seq.html"><strong aria-hidden="true">3.7.</strong> 序列</a></li><li class="chapter-item expanded "><a href="guide-err.html"><strong aria-hidden="true">3.8.</strong> 错误处理</a></li></ol></li><li class="chapter-item expanded "><a href="portability.html"><strong aria-hidden="true">4.</strong> 可移植性</a></li><li class="chapter-item expanded "><a href="update.html"><strong aria-hidden="true">5.</strong> 更新</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="update-0.5.html"><strong aria-hidden="true">5.1.</strong> 更新到 0.5</a></li><li class="chapter-item expanded "><a href="update-0.6.html"><strong aria-hidden="true">5.2.</strong> 更新到 0.6</a></li><li class="chapter-item expanded "><a href="update-0.7.html"><strong aria-hidden="true">5.3.</strong> 更新到 0.7</a></li></ol></li><li class="chapter-item expanded "><a href="contributing.html"><strong aria-hidden="true">6.</strong> 贡献</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="contrib-doc.html"><strong aria-hidden="true">6.1.</strong> 文档</a></li><li class="chapter-item expanded "><a href="contrib-scope.html"><strong aria-hidden="true">6.2.</strong> Scope</a></li><li class="chapter-item expanded "><a href="contrib-test.html"><strong aria-hidden="true">6.3.</strong> 测试</a></li><li class="chapter-item expanded "><a href="contrib-bench.html"><strong aria-hidden="true">6.4.</strong> 基准</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                
                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                        
                    </div>

                    <h1 class="menu-title">The Rust Rand Book</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>
                        
                    </div>
                </div>

                
                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>
                

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1><a class="header" href="#getting-started" id="getting-started">Getting Started</a></h1>
<h1><a class="header" href="#入门指南" id="入门指南">入门指南</a></h1>
<blockquote>
<p><a href="https://github.com/rust-random/book/blob/master/src/guide-start.md">guide-start.md</a><br />
commit: 09b9f3ba87c8ee7c0480aceaefce4028d01cf592 <br />
本章译文最后维护日期：2020-11-21</p>
</blockquote>
<p>下面我们列举了一个简短的例子。更多信息，请参考<a href="https://rust-random.github.io/rand/rand/index.html">API文档</a>或<a href="guide.html">指南</a>。</p>
<p>让我们以一个例子开始（<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=4cad6600b21578cfa22009c281c780fe">playground链接</a>）：</p>
<pre><pre class="playground"><code class="language-rust editable"><span class="boring">extern crate rand;
</span>// 从预导入包(prelude)中导入常用的程序项(items)：
use rand::prelude::*;

fn main() {
    // 我们可以直接使用 random()。它可以生成许多常见类型的值。
    let x: u8 = random();
    println!(&quot;{}&quot;, x);

    if random() { // 产生一个布尔值
        println!(&quot;Heads!&quot;);
    }

    // 如果我们想要更明确一点（也更有效率一点），我们可以为线程级随机生成器(thread-local generator)创建一个句柄：
    let mut rng = thread_rng();
    if rng.gen() { // 布尔随机
        let x: f64 = rng.gen(); // 在区间[0, 1)之间浮点随机数
        let y = rng.gen_range(-10.0, 10.0);
        println!(&quot;x is: {}&quot;, x);
        println!(&quot;y is: {}&quot;, y);
        println!(&quot;Number from 0 to 9: {}&quot;, rng.gen_range(0, 10));
    }
    
    // 有时直接使用某个分布方式(distribution)也很有用：
    let distr = rand::distributions::Uniform::new_inclusive(1, 100);
    let mut nums = [0i32; 3];
    for x in &amp;mut nums {
        *x = rng.sample(distr);
    }
    println!(&quot;Some numbers: {:?}&quot;, nums);
    
    // 我们还可以用它来和迭代器或切片交互：
    let arrows_iter = &quot;➡⬈⬆⬉⬅⬋⬇⬊&quot;.chars();
    println!(&quot;Lets go in this direction: {}&quot;, arrows_iter.choose(&amp;mut rng).unwrap());
    let mut nums = [1, 2, 3, 4, 5];
    nums.shuffle(&amp;mut rng);
    println!(&quot;I shuffled my {:?}&quot;, nums);
}
</code></pre></pre>
<p>你可能注意到的第一件事是我们从<a href="https://rust-random.github.io/rand/rand/prelude/index.html">预导入包(prelude)</a>中导入了所有的程序项。这是 <code>use</code> rand 的一个偷懒的方式，这个就跟<a href="https://doc.rust-lang.org/std/prelude/index.html">标准库的预导入包</a>一样，只导入最常用的程序项。
如果不想使用预导入包(prelude)，那请记住导入 <a href="https://rust-random.github.io/rand/rand/trait.Rng.html"><code>Rng</code></a> trait!</p>
<p>Rand库可以根据需要自动初始化一个安全的线程级随机生成器。这可以通过函数 <a href="https://rust-random.github.io/rand/rand/fn.thread_rng.html"><code>thread_rng</code></a> 和 <a href="https://rust-random.github.io/rand/rand/fn.random.html"><code>random</code></a> 来访问。
有关这个主题的更多信息，请参见<a href="guide-gen.html">随机生成器</a>。</p>
<p>虽然函数 <a href="https://rust-random.github.io/rand/rand/fn.random.html"><code>random</code></a> 只能以<a href="https://rust-random.github.io/rand/rand/distributions/struct.Standard.html"><code>Standard</code></a>（典型依赖）的方式获取抽样值(sample values)，但 <a href="https://rust-random.github.io/rand/rand/fn.thread_rng.html"><code>thread_rng</code></a> 可以给你一个生成器的句柄。
所有生成器都实现了 <a href="https://rust-random.github.io/rand/rand/trait.Rng.html"><code>Rng</code></a> trait，它们都提供了上面示例中使用的 <a href="https://rust-random.github.io/rand/rand/trait.Rng.html#method.gen"><code>gen</code></a>、<a href="https://rust-random.github.io/rand/rand/trait.Rng.html#method.gen_range"><code>gen_range</code></a> 和 <a href="https://rust-random.github.io/rand/rand/trait.Rng.html#method.sample"><code>sample</code></a> 这些方法。</p>
<p>Rand还通过 <a href="https://rust-random.github.io/rand/rand/seq/trait.IteratorRandom.html"><code>IteratorRandom</code></a> 和 <a href="https://rust-random.github.io/rand/rand/seq/trait.SliceRandom.html"><code>SliceRandom</code></a> 这两个额外的 trait 提供了针对迭代器和切片的函数。</p>
<h2><a class="header" href="#fixed-seed-rngs" id="fixed-seed-rngs">Fixed seed RNGs</a></h2>
<h2><a class="header" href="#固定种子随机数生成器" id="固定种子随机数生成器">固定种子随机数生成器</a></h2>
<p>您可能已经注意到在上面示例中 <code>thread_rng()</code> 的使用，想知道如何指定固定的随机数种子。
为此，需要先指定一个RNG(随机数生成器)，然后使用像 <a href="https://rust-random.github.io/rand/rand/trait.SeedableRng.html#method.seed_from_u64"><code>seed_from_u64</code></a> 或<a href="https://rust-random.github.io/rand/rand/trait.SeedableRng.html#tymethod.from_seed"><code>from_seed</code></a> 这样的方法。</p>
<p>注意 <a href="https://rust-random.github.io/rand/rand/trait.SeedableRng.html#method.seed_from_u64"><code>seed_from_u64</code></a> <strong>不适合用于加密</strong>，因为单个 <code>u64</code> 不能提供足够的熵来安全地为RNG置种(seeding)。
所有用于加密的RNG都是通过 <a href="https://rust-random.github.io/rand/rand/trait.SeedableRng.html#tymethod.from_seed"><code>from_seed</code></a> 来接收更合适的随机数种子的。</p>
<p>下面我们使用了 <code>ChaCha8Rng</code>，因为它速度快，可移植性好，质量也好。
更多RNG请参阅 <a href="guide-rngs.html">RNGs</a> 部分，但是如果您关心可重现的结果，请避免使用 <code>SmallRng</code> 和 <code>StdRng</code>。</p>
<pre><pre class="playground"><code class="language-rust editable">extern crate rand;
extern crate rand_chacha;

use rand::{Rng, SeedableRng};

fn main() {
    let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(10);
    println!(&quot;Random f32: {}&quot;, rng.gen::&lt;f32&gt;());
}
</code></pre></pre>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        
                            <a rel="prev" href="intro.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>
                        

                        
                            <a rel="next" href="crates.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>
                        

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                
                    <a rel="prev" href="intro.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a rel="next" href="crates.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
                
            </nav>

        </div>

        

        

        

        
        <script type="text/javascript">
            window.playground_copyable = true;
        </script>
        

        

        
        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
        

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->
        

        

    </body>
</html>
